﻿using System;
using UnityEngine;
using System.IO.Ports;

public class SerialCommTest : MonoBehaviour
{
    private SerialPort serialPort;
    private float readTimer;

    void OpenSerialPort()
    {
        try
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
            serialPort.Open();
        }
        catch (Exception e)
        {
            Debug.Log("Serial communication error!");
            Debug.Log(e.Message);
            Debug.Log(e.StackTrace);
        }
    }

    void Start()
    {
        serialPort = new SerialPort();
        serialPort.PortName = "/dev/ttyUSB0";
        serialPort.BaudRate = 9600;
        OpenSerialPort();
    }
    
    void Update()
    {
        readTimer += Time.deltaTime;
        if (readTimer > 0.25f)
        {
            if (serialPort.IsOpen)
            {
                try
                {
                    if (serialPort.BytesToRead > 0)
                    {
                        string s = serialPort.ReadExisting();
                        Debug.Log(s);
                    }
                }
                catch (Exception e)
                {
                    Debug.Log("Serial communication error!");
                    Debug.Log(e.Message);
                    Debug.Log(e.StackTrace);
                    serialPort.Close();
                }
            }
            else
            {
                OpenSerialPort();
            }
            readTimer = 0;
        }
    }
}